﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace TestNPOIPro
{
  public class JsonHelper
  {
    /// <summary>
    /// 获取JToken的字符串值
    /// </summary>
    /// <returns></returns>
    public static string GetJTokenValue(JToken jt)
    {
      if (jt == null || jt.ToString() == "")
        return "";
      return jt.ToString();
    }

    public static T GetJTokenValue<T>(JToken jt, T tDef)
    {
      T sResult = tDef;
      if (jt == null)
      {
        sResult = tDef;

      }
      else if (tDef is int)
      {
        if (jt.ToString().Trim() == "")
          sResult = tDef;
        else
          sResult = (T)(object)(Convert.ToInt32(jt.ToString().Trim()));
      }
      else if (tDef is double)
      {
        if (jt.ToString().Trim() == "")
          sResult = tDef;
        else
          sResult = (T)(object)(Convert.ToDouble(jt.ToString().Trim()));
      }
      else if (tDef is float)
      {
        if (jt.ToString().Trim() == "")
          sResult = tDef;
        else
          sResult = (T)(object)(Convert.ToDouble(jt.ToString().Trim()));
      }
      else if (tDef is bool)
      {
        if (jt.ToString().Trim() == "")
          sResult = tDef;
        else
          sResult = (T)(object)(jt.ToString().Trim() == "1" || jt.ToString().ToLower().Trim() == "true");
      }
      else
      {
        sResult = (T)(object)(jt.ToString().Trim());
      }
      return sResult;
    }

    private static string myConvert(object obj, string defVal = "")
    {
      if (obj == null)
        return defVal;
      else return obj.ToString();
    }

    public static string ToJson(object obj)
    {
      return JsonConvert.SerializeObject(obj);
    }

    public static T JsonTo<T>(string json)
    {
      return JsonConvert.DeserializeObject<T>(json);
    }

  }
}
